package com.example.camera;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.RectF;
import android.view.SurfaceHolder;

public class DrawThread extends Thread {

	private boolean runFlag = false;
	private SurfaceHolder surfaceHolder;
	private Bitmap picture;
	private Matrix matrix;
	private long prevTime;
	private Paint paint;

	public DrawThread(SurfaceHolder surfaceHolder, Resources resources) {
		this.surfaceHolder = surfaceHolder;
		picture = BitmapFactory.decodeResource(resources,
				R.drawable.ic_launcher);
		matrix = new Matrix();
		prevTime = System.currentTimeMillis();
	}

	public void setRunning(boolean run) {
		runFlag = run;
	}

	@Override
	public void run() {
		Canvas canvas;
		while (runFlag)
		{
			long now = System.currentTimeMillis();
			long elapsedTime = now - prevTime;
			
			if (elapsedTime > 1)
			{
				prevTime = now;
			}
			canvas = null;
			try
			{
				canvas = surfaceHolder.lockCanvas(null);
				synchronized (surfaceHolder) {
					matrix.setRectToRect(
							new RectF(0,0,picture.getWidth(), picture.getHeight()),
							new RectF(0,0,canvas.getWidth(), canvas.getHeight()),
							Matrix.ScaleToFit.CENTER);
				canvas.drawBitmap(picture, matrix,  paint);
				}
			}
			finally
			{
				if (canvas != null)
				{
					surfaceHolder.unlockCanvasAndPost(canvas);
				}
			}
		}
	}
	
	public void setBitmap(Bitmap bitmap)
	{
		picture = bitmap;
	}
}
